﻿using OpenCvSharp;
using System.Runtime.InteropServices;
using ZXing;
using ZXing.Common;

namespace UDI.Core
{
    internal class LabelTool
    {
        /// <summary>
        /// zbar解析128
        /// </summary>
        /// <param name="cut"></param>
        /// <returns></returns>
        public static List<string>? ZbarBarCode(Mat cut)
        {
            Cv2.ImShow(Guid.NewGuid().ToString(), cut);
            List<string>? result;
            using (var scanner = new ZBar.ImageScanner())
            {
                Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(cut);
                //OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
                var symbols = scanner.Scan(bitmap);

                result = symbols?
                    .Where(t =>
                    t.Data.StartsWith("01")
                    || t.Data.StartsWith("10")
                    || t.Data.StartsWith("11")
                    || t.Data.StartsWith("17")
                    || t.Data.StartsWith("21")
                    )
                    .Select(t => t.Data).ToList();
                bitmap.Dispose();
                GC.Collect();
            }
            return result;
        }


        /// <summary>
        /// zxing解析DM
        /// </summary>
        /// <param name="cut"></param>
        /// <returns></returns>
        public static string? ZxingDMCode(Mat cut)
        {
            //Cv2.ImShow(Guid.NewGuid().ToString(), cut);

            //Mat转byte[]
            var bytes = new byte[cut.Total() * 3];//这里必须乘以通道数，不然数组越界，也可以用w*h*c，差不多
            Marshal.Copy(cut.Data, bytes, 0, bytes.Length);

            //zxing 解析dm码
            //Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(cut);

            var reader = new ZXing.Datamatrix.DataMatrixReader();
            // Convert the Bitmap to a BinaryBitmap
            var luminanceSource = new RGBLuminanceSource(bytes, cut.Width, cut.Height);
            var binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

            var result = reader.decode(binaryBitmap)?.Text;
            if (result != null &&
                (result.StartsWith("01")
                    || result.StartsWith("10")
                    || result.StartsWith("11")
                    || result.StartsWith("17")
                    || result.StartsWith("21")))
            {
                return result;
            }
            else
            {
                return null;
            }
        }
    }
}
